package com.lhkj.ct.base.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

public class MyLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    /**
     * yyyy-MM-dd HH:mm:ss
     */
    private static final Pattern DEFAULT_DATETIME_PATTERN = Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$");

    /**
     * yyyy-MM-dd HH:mm
     */
    private static final Pattern YYYY_MM_DD_HH_MM_PATTERN = Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}$");

    /**
     * yyyy-MM-dd HH:mm
     */
    private static final Pattern YYYY_MM_DD_PATTERN = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}$");

    /**
     * yyyy-MM-ddTHH:mm:ss.SSSZ
     */
    private static final Pattern YYYY_MM_DD_T_HH_MM_SS_ZONE_PATTERN = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}[A-Z]$");

    /**
     * 时间戳
     */
    private static final Pattern TIMESTAMP_PATTERN = Pattern.compile("^[\\d]*$");

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String source = jsonParser.getValueAsString();
        if (StringUtils.isBlank(source)) {
            return null;
        }
        // yyyy-MM-dd HH:mm:ss格式
        if (DEFAULT_DATETIME_PATTERN.matcher(source).matches()){
            return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        // yyyy-MM-dd HH:mm格式
        if (YYYY_MM_DD_HH_MM_PATTERN.matcher(source).matches()){
            return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        }
        // yyyy-MM-dd格式
        if (YYYY_MM_DD_PATTERN.matcher(source).matches()){
            return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
        }
        // yyyy-MM-ddTHH:mm:ss.SSSZ格式
        if (YYYY_MM_DD_T_HH_MM_SS_ZONE_PATTERN.matcher(source).matches()){
            return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
        }
        // 时间戳
        if (TIMESTAMP_PATTERN.matcher(source).matches()){
            long timeStamp = Long.parseLong(source);
            return Instant.ofEpochMilli(timeStamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
        }
        return LocalDateTime.parse(source);
    }

}
